package org.egomsl.mw.benchmark;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.orc.mapred.OrcStruct;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.orc.mapreduce.OrcInputFormat;

import java.io.IOException;


public class OrcMapReduce {

    public static class ORCMapper extends
            Mapper<NullWritable, OrcStruct, Text, IntWritable> {
        public void map(NullWritable key, OrcStruct value, Context output)
                throws IOException, InterruptedException {
            output.write(
                    (Text)value.getFieldValue("appsflyer_device_id"),
                    new IntWritable(1));
        }
    }

    public static class ORCReducer extends Reducer<Text, IntWritable, Text, IntWritable> {

        // 实现具体mreduce业务逻辑
        @Override
        public void reduce(Text key, Iterable<IntWritable> values,
                           Reducer<Text, IntWritable, Text, IntWritable>.Context output)
                throws IOException, InterruptedException {
            int count = 0;
            for(IntWritable i : values) {
                count += i.get();
            }

            output.write(key, new IntWritable(count));
        }
    }

    public static void main(String args[]) throws Exception {

        Configuration conf = new Configuration();

        Job job = Job.getInstance(conf, "ORC Test");
        job.setJarByClass(OrcMapReduce.class);
        job.setMapperClass(ORCMapper.class);
        job.setReducerClass(ORCReducer.class);

        job.setInputFormatClass(OrcInputFormat.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));


        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
